package com.zhenyi.fenda.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.utils.AuthUtils;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.URLUtil;

public class AuthInterceptor implements Interceptor {

	String HOST = PropKit.get("FD_HOST", "http://app.cenjiawen.com/fd");
	String APP_ID = PropKit.get("FD_APP_ID", "wx24524e8b092948cf");

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		ApiConfigKit.getApiConfig(APP_ID);
		System.out.println(IpKit.getRealIpV2(controller.getRequest()));
		if (AuthUtils.verify(controller)) {
			inv.invoke();
		} else {
			LogKit.info("not verify");
			// HttpServletRequest request = controller.getRequest();
			// String url = request.getRequestURL().toString();
			// String queryurl = request.getQueryString();
			// if (StrKit.notBlank(queryurl)) {
			// url = url + "?" + queryurl;
			// }
			// // controller.renderError(401);
			// controller.redirect("/fd/auth?STATE=" + URLUtil.encode(url));
			String rd = HOST + "/auth";
			rd = URLUtil.encode(rd);
			String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={}&redirect_uri={}&response_type=code&scope={}&state={}#wechat_redirect";
			String request = getRequestUrl(inv);
			String scope = "snsapi_userinfo";// snsapi_userinfo,snsapi_base
			url = StrFormatter.format(url, APP_ID, rd, scope, URLUtil.encode(request));
			// LogKit.info("rdUrl:" + url);
			// LogKit.info("APP_ID:" + APP_ID);
			// LogKit.info("HOST:" + HOST);
			controller.redirect(url);
			return;
		}
	}

	private String getRequestUrl(Invocation inv) {
		String url = inv.getController().getRequest().getRequestURL().toString();
		String queryurl = inv.getController().getRequest().getQueryString();
		if (StrKit.notBlank(queryurl)) {
			url = url + "?" + queryurl;
		}
		return url;
	}
}
